define([
    'require',
    'jquery',
    'message',
    'bigwe_component',
    'constants',
    'usergroup_manage',
    'artCategoryHandle',
    'bigwe_utils',
    'tooltip',
    'popover',
    'pagination',
    'combiner',
    'header',
    'api',
    'nav',
    'spread_filter',
], function(require, $, ShowTitleMessage, bc, c) {
    /*bs, header, bu*/
    var groupManage = require('usergroup_manage'),
        category = require('artCategoryHandle'),
        util = require('bigwe_utils');
    var groupManageConfig = {
        requestType: 'get',
        groupType: 'article',
        addNewUrl: '/my_assets/add_ucg', // 添加分组数据接口
        addParamName: 'cgn', // 添加分组的参数名
        deleteUrl: '/my_assets/del_cg', // 删除分组数据接口
        deleteParamName: 'cgid', // 删除分组的参数名
        modifyUrl: '/my_assets/up_cgn',
        modifyParam: { // 修改分组的参数名
            groupId: 'cgid',
            groupName: 'cgn'
        },
        userGroupData: null, // 未加载请定义成null 加载完成如果没有数据赋值成空数组
        // 列表展示数据赋值
        deleteCallback: function(data, deleteID) {
            var del_tag = $('.article-tag span[cgid="' + deleteID + '"]');
            if (del_tag.hasClass('green')) {
                delete param.cgid;
                param['p'] = 1;
                isOk = true;
                record.option();
                $(".article-tag > div > span").eq(0).addClass('green');
            }
            del_tag.remove();
        },
        addCallback: function(data) {
            if (typeof data === 'string') data = $.parseJSON(data);
            $(".article-tag > div").append("<span cgid='" + data.id + "'>" + data.name + "</span>");
            // cg(data_articleid,data.id);
        },
        modifyCallback: function(data) {
            tag_list(this.userGroupData);
        }
    }


    /*
     * 分组
     */
    groupManage.init(groupManageConfig);
    $.ajax({
        type: 'get',
        cache: 'false',
        dataType: 'json',
        url: '/my_assets/mg_ls',
        data: {
            rt: 'article'
        },
        success: function(data) {
            if (data.ret == 0) {
                var group = data.data;
                tag_list(group);
                groupManageConfig.userGroupData = group;
            }
        }
    });

    function tag_list(tagArray) {
        var tag_cont = $(".article-tag > div");
        var cgid = tag_cont.find('span.green').attr('cgid');
        tag_cont.find("span").eq(0).siblings().remove();
        var html = '';
        for (var key in tagArray) {
            if (tagArray[key] != '') html += "<span cgid='" + tagArray[key].id + "'>" + tagArray[key].group_name + "</span>";
        }
        tag_cont.append(html);
        tag_cont.find('[cgid="' + cgid + '"]').addClass('green').siblings().removeClass('green');
    }

    var data_articleid;
    var isOk = true;
    var param = {
        p: 1,
    }

    var record = {
        option: function() {
            this.init(param);
        },
        init: function(event) {
            ShowTitleMessage.show('正在加载...');
            $.ajax({
                type: "post",
                dataType: "json",
                url: "/my_assets/get_art_ls",
                data: event,
                success: function(data) {
                    var arts_html = '';
                    var release = '';
                    var cds = '';

                    if (data.msg == 'data not found!') {
                        $('.total_number').text(0);
                        $('.article-list').empty().append("<p>暂无文章！</p>");
                        record.paging(0);
                    } else {
                        $('.total_number').text(data.total_number);
                        var arts = data.articles;
                        for (i in arts) {
                            var art = arts[i];

                            var cs = art.yc * 1; //原创标识
                            var type = art.msg_type_cd; //文章类型
                            var _igy = art.article_integrity; //文章

                            // var source_icon = (art.source == 'bigwe.com' ? '' : (art.source == 'toutiao.com' ? 'icon-icontoutiao' : 'icon-weixin'));
                            var copyright_img = (cs == 1 || cs == 2) ? '<img src="/Public/static/images/original' + (art.source == 'bigwe.com' ? '1' : '2') + '.png" alt="" class="original"/>' : '';
                            var time = (new Date(art.publish_time_millis * 1)).format('yyyy-MM-dd hh:mm');

                            if (art.need_publish == 0) {
                                if (_igy == 0) {
                                    release = '<p><span class="iconfont icon-gantanhao" data-trigger="hover" data-toggle="popover" data-placement="bottom" title="文章不完整" data-content="请先编辑好文章的标题、正文和标签"></span></p>';
                                } else {
                                    release = '<p>未发布</p>';
                                }
                            } else if (art.need_publish == 1) {
                                release = '<p class="red">待发布</p>';
                            } else {
                                release = '<p class="green">已发布</p>';
                            }

                            arts_html += '<div class="article-sub">' +
                                ' <div class="article-title"><input type="checkbox"><a href="/article/index/p/' + art.cd + '" target="_blank" title="' + art.title + '">' + art.title + '</a></div>' +
                                '' + release +
                                '<div class="picture">' +
                                '<a href="/article/index/p/' + art.cd + '" target="_blank"><img src="' + util.imgTimthumb(art.cover_img_url,130,80) + '" alt="" onerror="this.src=\'' + c.resPath + '/images/wuyulantu.png\';"></a>' + copyright_img +
                                '</div>' +
                                '<div class="article-sub-taxt" data-articleid="' + art.cd + '" data-title="' + art.title + '" data-img="' + data.img_cdn + art.cover_img_url + '" data-url="/article/index/p/' + art.cd + '" data-id="' + art.cd + '">' +
                                '<p>' + (art.summary || '') + '</p>' +
                                '<span class="iconfont platform-icon icon-iconbigwe"></span>' +
                                '<span class="article-account">' + art.user_nicename + '</span>' +
                                '<span class="article-time">' + time + '</span>' +
                                '<span class="glyphicon glyphicon-trash icon-delete article-collect" data-toggle="tooltip" title="删除"></span>';
                            if (_igy != 0 || art.need_publish == 2) {
                                arts_html += '<span class="iconfont article-merge icon-box" addcar-event data-toggle="tooltip" title="加入合成器"></span>';
                            }
                            arts_html += '<span class="iconfont mobile-packet icon-huhuan"  data-toggle="tooltip" title="移动分组"></span>';
                            // <span class="iconfont icon-tongbu" data-toggle="tooltip" data-original-title="同步到微信" synchro></span>
                            if (type == 'article' && (art.need_publish == 0 || art.need_publish == 1)) {
                                arts_html += '<span class="iconfont icon-pen1 art_btn_bj" data-toggle="tooltip" data-original-title="编辑"></span>';
                            }
                            arts_html += '</div></div>';
                            cds += ',' + art.cd
                        }
                        $('.article-list').empty().append(arts_html);
                        $('[data-toggle="tooltip"]').tooltip({
                            trigger: 'hover'
                        });
                        $("[data-toggle='popover']").popover();
                        if (!$(".batch-selection").is(':hidden')) {
                            $(".article-title > input").show();
                            check_change();
                        }
                        if (isOk == true) {
                            record.paging(data.total_number);
                        }
                    }
                    ShowTitleMessage.hide();
                }
            })
        },
        paging: function(event) {
            $('.paging').hide();
            var cur_page = param['p'] - 1;
            $("#article_paging").pagination(event, {
                num_edge_entries: 2,
                num_display_entries: 4,
                items_per_page: 10,
                current_page: cur_page,
                prev_text: '上一页',
                next_text: '下一页',
                callback: function(_index, jq) {
                    if (isOk == true) {
                        return;
                    } else {
                        param['p'] = _index + 1;
                        record.option();
                    }
                }
            });
            isOk = false;
            if (event > 10) {
                $('.paging').show();
            }
        },
        addGrouping: function(obj, event) {
            var _this = $(obj);

            $("body").append('<div class="add_grouping">' +
                '<img src="/Public/static/images/Triangle-up.png">' +
                '<p>您还没有分组，请添加分组</p>' +
                '<input type="text" value="" maxlength="30" class="sure_val"><br/>' +
                '<button type="button" class="btn-success sure">确定</button>' +
                '<button type="button" class="btn-default btn_cancel" onclick="$(this).parent().remove()">取消</button>' +
                '</p>' +
                '</div>');
            $('.add_grouping').css({
                left: _this.offset().left - $('.add_grouping').width() / 2,
                top: _this.offset().top + $('.add_grouping').height() / 3,
            })
            $('.sure_val').focus();
            $('.sure_val').on('keyup', function(e) {
                e = e || event;
                if (e.keyCode == 13) {
                    //判断是否按下的enter按键(回车键)
                    $('.add_grouping > .sure').trigger('click');
                }
            });
            $('.add_grouping > .sure').click(function() {
                    var _group = $('.sure_val').val();
                    if (_group) {
                        data_articleid = _this.parent().attr('data-articleid');
                        $(this).parent().remove();
                        commonAddGroup(_group);
                    } else {
                        ShowTitleMessage.show('请输入分组名', showTime);
                        $('.sure_val').focus();
                    }
                })
                /**
                 * 点击其他地方隐藏
                 */
            $(document).bind('click.add_grouping', function(e) {
                var e = e || window.event; //浏览器兼容性 
                var elem = e.target || e.srcElement;
                while (elem) { //循环判断至跟节点，防止点击的是div子元素 
                    if (elem.className && elem.className == 'add_grouping') {
                        return;
                    }
                    elem = elem.parentNode;
                }

                $(".add_grouping").remove(); //点击的不是div或其子元素 
                $(document).unbind("click.add_grouping");
            });
        }
    }

    $('.selectpicker').selectpicker();

    $(function() {
        record.option();
        /*领域点击*/
        $(".article-tag > div").on("click", "span", function() {
            if ($(this).hasClass("green")) {
                return;
            } else {
                $(this).addClass("green").siblings().removeClass("green");

                param['cgid'] = $(this).attr('cgid');
                param['p'] = 1;
                isOk = true;

                record.option();
                $(".batch-selection input[type='checkbox']")[0].indeterminate = false;
                $(".batch-selection input[type='checkbox']").removeAttr('checked');
                $('.bat_check').text('无');
            }
        });

        /*搜索*/

        $('.search_btn').click(function() {
            param['key'] = $('.search_input').val();
            param['p'] = 1;
            isOk = true;
            record.option();
        })
        $('.search_input').change(function() {
            if ($(this).val() != param['key']) {
                param['key'] = $(this).val();
                param['p'] = 1;
                isOk = true;
                record.option();
            }
        })

        $(".filter-select").on('change', 'select', function() {
            var name = $(this).attr('name');
            var val = $(this).val();
            if (name == 'need_publish') {
                param['need_publish'] = val;
            } else {
                param['yc'] = val;
            }

            isOk = true;
            param['p'] = 1;

            record.option();
        })

        /**
         * 绑定编辑事件
         */
        $('.article-list').on('click', '.art_btn_bj', function() {
            window.location.href = "/edit_text?edit_type=1&cd=" + $(this).parent().attr('data-id');
        });

        /*移动分组*/
        $(".article-list").on("click", ".mobile-packet", groupmove);
        $(document).on('click', '.category-tab .category', cg);
        /*批量管理*/
        $(".batch").click(function() {
            if ($(this).text() == "批量管理") {
                $(this).text("退出管理");
                $(".filter").hide();
                $(".batch-selection").show();
                $(".article-title > input").show();
                $(this).addClass("manage");
            } else {
                $(this).text("批量管理");
                $(".filter").show();
                $(".batch-selection").hide();
                $(".article-title > input").hide();
                $(this).removeClass("manage");
            }
        });

        /*全选*/
        $(".batch-selection > label :checkbox").change(check_change);
        $(".article-list").on("change", "input[type='checkbox']", check_change);

        /*批量移动分组*/
        $(".batch-grouping").click(groupmove);
        /*删除素材*/
        $(".article-list").on("click", ".article-collect", function(e) {
            if ($('.add_grouping') || $('.category')) {
                $('.add_grouping').remove();
                $('.category').remove();
            }
            var _this = $(this);
            var text = $(".total_number").text();
            var target_id = _this.parent().attr("data-id");
            e.stopPropagation();
            bc.deleteConfirmShowBottom({
                obj: this,
                fun: function() {
                    _this.parents(".article-sub").remove();
                    // $(".total_number").text(text - 1);
                    deletedata(target_id);
                }
            });
        });
        /*批量删除*/
        $(".batch-del").click(function() {
            var object = "";
            var _this = $(this);
            bc.deleteConfirmShowBottom({
                obj: this,
                fun: function() {
                    // $(".batch-selection input").attr("checked", false);
                    $(".article-list input").each(function() {
                        if (this.checked) {
                            if (object.length > 1) {
                                object += ",";
                            }
                            object += $(this).parents(".article-sub").find(".article-sub-taxt").attr("data-id");
                            $(this).parents(".article-sub").remove();
                        }
                    });
                    deletedata(object);
                }
            })
        });

        // /*同步素材至微信*/
        // $('.article-list').on("mouseover mouseout", '[synchro]', function(event) {
        //     var b = $(this),
        //         $back = $('<div class="synchro_state" style="left: 764.5px;"> <div class="th"> <p>时间</p> <p>公众号</p> <p>状态</p> </div> <div class="tr"> <p>2017-02-10 16:10</p> <p class="tr_name">小莫和他的朋友</p> <p class="green">同步成功</p> </div> <div class="tr"> <p>2017-02-10 16:10</p> <p class="tr_name">小莫和他的朋友</p> <p><span class="red">同步失败</span>(无效的图片)</p> </div> </div>');
        //     if (event.type == "mouseover") {
        //         $back.insertAfter(b);

        //         $back.css({
        //             "left": (b.offset().left - 340) + "px",
        //         });
        //     } else if (event.type == "mouseout") {
        //         $('.synchro_state').remove();
        //     } else if (event.type == 'click') {
        //         alert(1);
        //     }
        // });
        // $('.article-list').on("click", '[synchro]', function(event) {
        //     console.log(1);
        //     $('.synchro_state').remove();
        // });
    })

    /*移动分组*/
    function groupmove(e) {
        e = e || event;
        e.stopPropagation();
        var groupData = groupManageConfig.userGroupData;
        var obj = event.srcElement.type;
        var groupsHtml = '';

        if ($('.delete_confirm')) {
            $('.delete_confirm').remove();
        }
        if (groupData.length < 1) {
            record.addGrouping(this);
            return;
        }
        if (obj == 'button') {
            var num = "";
            $(".article-title :checkbox").each(function() {
                if (this.checked) {
                    if (num.length > 1) {
                        num += ",";
                    }
                    num += $(this).parents(".article-sub").find(".article-sub-taxt").attr("data-id");
                }
            });
            groupsHtml += '<div article_group="' + num + '" class="category-tab" style="display: block;">';
        } else {
            groupsHtml += '<div article_group="' + $(this).parent().attr('data-articleid') + '" class="category-tab" style="display: block;">';
        }

        var thisGroupId = $(this).attr('group_id');
        var cacl = 0;
        for (i in groupData) {
            if (groupData[i].id * 1 == thisGroupId * 1) continue;
            if (cacl == 0) {
                groupsHtml += '<div class="category" target_group="' + groupData[i].id + '"><div class="arrow"></div>' + groupData[i].group_name + '</div>';
                cacl++;
            } else {
                groupsHtml += '<div class="category" target_group="' + groupData[i].id + '">' + groupData[i].group_name + '</div>';
                cacl++;
            }
        }
        groupsHtml += '<div class="category" target_group="-1">移出分组</div>';
        groupsHtml += '</div>';

        var left = 0,
            top = 0;

        var thisHeight = $(this).outerHeight(),
            thisWidth = $(this).outerWidth(),
            thisTop = $(this).offset().top,
            thisLeft = $(this).offset().left;
        if (obj == 'button') {
            left = thisLeft + thisWidth - thisWidth / 2 + 55;
            top = thisTop + thisHeight - thisHeight / 2 - 20;
        } else {
            left = thisLeft + thisWidth - thisWidth / 2 + 25;
            top = thisTop + thisHeight - thisHeight / 2 - 20;
        }

        $('.category-tab').remove();
        $('body').append($(groupsHtml).css({
            left: left,
            top: top
        }));

        $(document).bind('click.category', function() {
            $('.category-tab').remove();
            $(document).unbind('click.category');
        });
    }

    function cg(s, d) {
        if (d) {
            var id = s,
                cgid = d;
        } else {
            var id = $(this).parent().attr('article_group'),
                cgid = $(this).attr('target_group');
        }

        if (cgid != -1) {
            var _url = '/my_assets/cg',
                _data = {
                    rt: 'article',
                    cgid: cgid,
                    cd: id,
                };
        } else {
            var _url = '/my_assets/del_res_cg',
                _data = {
                    rt: 'article',
                    cd: id,
                };
        }
        $.ajax({
            type: 'post',
            url: _url,
            data: _data,
            success: function(data) {
                if (data.msg == 'ok') {
                    ShowTitleMessage.show('操作成功！', 1500);
                    group_id();
                    if ($(".article-tag > div > span.green").text() != '全部') {
                        if (!$(".batch-selection").is(':hidden')) {
                            $(".batch-selection input[type='checkbox']").prop('checked', false);
                            $(".batch-selection input[type='checkbox']")[0].indeterminate = false;
                            $('.batch-selection > button').prop('disabled', true);
                            $('.bat_check').text('无');
                        }
                        isOk = true;
                        record.option();
                    }
                } else {
                    ShowTitleMessage.showWarning('您还没有分组或者该图文已存在您唯一分组中', 1500);
                }
            }
        })
    };

    /*删除素材*/
    function deletedata(targetid) {
        $.ajax({
            type: 'get',
            dataType: 'json',
            url: '/my_assets/del',
            data: {
                id: targetid,
                rt: 'article',
            },
            success: function(data) {
                if (data.ret == 0) {
                    var chil_len = '';
                    $('.article-list').each(function() {
                        chil_len = $(this).children().length;
                    });
                    if (chil_len == 0 && param['p'] != 1) {
                        param['p'] -= 1;
                        isOk = true;
                    }
                    if (!$(".batch-selection").is(':hidden')) {
                        $(".batch-selection input[type='checkbox']").prop('checked', false);
                        $(".batch-selection input[type='checkbox']")[0].indeterminate = false;
                        $('.batch-selection > button').prop('disabled', true);
                        $('.bat_check').text('无');
                    }
                    record.option();
                    group_id();
                }
            }
        })
    }

    function check_change() {
        if ($(this).attr('name') == 'all') {
            if ($(this)[0].checked) {
                $(".article-title :checkbox").prop('checked', true);
                $('.batch-selection > button').removeAttr('disabled');
                $('.bat_check').text($('.article-list :checked').length + '篇');
            } else {
                $('.article-list input[type="checkbox"]').removeAttr('checked');
                $('.batch-selection > button').prop('disabled', true);
                $('.bat_check').text('无');
            }
        } else {
            var graphLen = $('.article-list input[type="checkbox"]').length,
                checkLen = $('.article-list :checked').length;
            var $checkAll = $(".batch-selection input[type='checkbox']");
            if (checkLen == 0) {
                $checkAll[0].indeterminate = false;
                $checkAll.removeAttr('checked');
                $('.batch-selection > button').prop('disabled', true);
                $('.bat_check').text('无');
            } else {
                $('.batch-selection > button').removeAttr('disabled');
                $('.bat_check').text(checkLen + '篇');
                if (graphLen != checkLen) {
                    $checkAll[0].indeterminate = true;
                } else {
                    $checkAll.prop('checked', 'checked');
                    $checkAll[0].indeterminate = false;
                }
            }
        }
    }

    /*分组文章数同步*/
    function group_id() {
        $.ajax({
            type: 'post',
            dataType: 'json',
            url: '/my_assets/mg_ls',
            data: {
                rt: 'article'
            },
            success: function(data) {
                var arts = data.data;
                for (var i in arts) {
                    $('[groupid=\"' + arts[i].id + '\"]').find('.battery-number').text(arts[i].group_num);
                }
            }
        });
    }
});
